package com.bluevally.microservice.user.dao;

import cn.zhonggu.utopay.framework.db.connection.DbType;
import cn.zhonggu.utopay.framework.db.operation.DbConnUtil;
import cn.zhonggu.utopay.framework.db.operation.DbOpTemplate;
import com.bluevally.framework.client.context.ThreadLocalHolder;
import org.apache.commons.collections.CollectionUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by lixiaoming on 16/2/29.
 */
public class CommonDao {

    public static<T> int dbNewRecord(T record) throws Exception {
        int rows = getObjectDbOpTemplate().dbNewRecord(record);
        return rows;
    }

    public static Date getDbSysDate() throws Exception {
        return DbConnUtil.getDbTime(ThreadLocalHolder.getDbConn());
    }

    public static<T> void updateOneRecord(T record, Object condition) throws Exception {
        getObjectDbOpTemplate().dbUpdateOneRecord(record,condition);
    }

    public static<T> List<T> queryRecords(String sql, Class<T> clazz) throws Exception {
        final DbOpTemplate<T> objectDbOpTemplate = getObjectDbOpTemplate();
        return objectDbOpTemplate.sql_queryRecords(sql, clazz);
    }

    public static<T> T queryRecord(T condition) throws Exception {
        final DbOpTemplate<T> objectDbOpTemplate = getObjectDbOpTemplate();
        return objectDbOpTemplate.queryRecord(condition);
    }


    public static List<Map> executeQuery(String sql) throws Exception {
        return getObjectDbOpTemplate().executeQuery(sql);
    }

    private static<T> DbOpTemplate<T> getObjectDbOpTemplate() throws SQLException {
        Connection dbConn = ThreadLocalHolder.getDbConn();
        return new DbOpTemplate<T>(dbConn, DbType.MYSQL);
    }

    public static int querySum(String sql) throws Exception {
        List<Map> maps = CommonDao.executeQuery(sql);
        int expect ;
        if (CollectionUtils.isEmpty(maps)) {
            expect = 0;
        } else {
            final Object sum = maps.get(0).get("sum");
            expect = sum==null?0: Integer.parseInt(""+ sum);
        }
        return expect;
    }
}
